import {
  getInspectionFileInfoByPage,
  addInspectionFileInfo,
  updateInspectionFileInfo,
  delInspectionFileInfo,
  exportInspectionFileInfo,
  uploadInspectionFileInfo,
  downloadInspectionFile,
  viewBaseInfo,
  getInspectPreviewUrl,
} from '@/services/product/inspectionFileInfo';
import { Ellipsis } from '@/components/Ellipsis';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Upload } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import moment from 'moment';
const InspectionFileInfo: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  const theid = props.theid;
  const thestate = props.thestate;
  const [fileList, setFileList] = useState();
  const columns: ProColumns[] = [
    // {
    // title: '序号',
    // dataIndex: 'index',
    // valueType: 'index',
    // width: 80,
    // },
    // {
    //   title: '文件链接',
    //   dataIndex: 'fileUrl',
    // },
    {
      title: '检验类型',
      dataIndex: 'inspectionType',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '文件名称',
      dataIndex: 'inspectionFileName',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '上传人',
      dataIndex: 'uploaderName',
      width: 90,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      width: 120,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '生产工序id',
    //   dataIndex: 'productManufactInforId',
    // },
    // {
    //   title: '入厂检id',
    //   dataIndex: 'productQualityId',
    // },
    // {
    //   title: '上传人id',
    //   dataIndex: 'uploaderId',
    // },
    // {
    //   title: '文件编号',
    //   dataIndex: 'inspectionFileCode',
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => [
        <a
          key="downloadKey"
          onClick={async () => {
            const filetype = record.inspectionFileName.split('.').pop();
            if (filetype == 'pdf' || filetype == 'png' || filetype == 'jpg') {
              // 可以预览的文件
              const url = await getInspectPreviewUrl(record);
              const w = window.open('about:blank');
              w.location.href = url.message;
              // const w = window.open('about:blank');
              // w.location.href = record.fileUrl;
            } else {
              // 不能预览，直接下载
              downloadInspectionFile({ inspectionFileId: record.id }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `${record.inspectionFileName}`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }
            // downloadInspectionFile({ inspectionFileId: record.id}).then((res) => {
            //   const aLink = document.createElement('a');
            //   document.body.appendChild(aLink);
            //   aLink.style.display = 'none';
            //   aLink.href = window.URL.createObjectURL(res);
            //   aLink.setAttribute('download', `${record.inspectionFileName}`);
            //   aLink.click();
            //   document.body.removeChild(aLink);
            // });
          }}
        >
          预览下载
        </a>,
        <a
          key="deleteKey"
          disabled={thestate == 3}
          onClick={() => {
            if (thestate != 3) {
              Modal.confirm({
                title: '删除',
                content: '确定要删除吗',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  await delInspectionFileInfo({ id: record.id });
                  actionRef.current!.reload();
                },
              });
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        const getuserlist = await viewBaseInfo(null);
        res.uploaderName = getuserlist.data.name;
        res.uploaderId = getuserlist.data.id;
        res.id = theid;
        res.inspectionType = '过程检验';
        res.uploadTime = moment().format('YYYY-MM-DD HH:mm:ss');
        const formData = new window.FormData();
        console.log('文件列表',fileList);
        fileList?.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        setFileList(undefined);
        console.log(res);
        const result = await uploadInspectionFileInfo(res);
        if (result != null) {
          message.success('上传成功');
          form.resetFields();
        }
        setConfirmLoading(false);
        setModalVisit(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading(false);
      });
  };

  const onFilesChange = async (info: any) => {
    setFileList(info.fileList);
  };
  const beforeUpload = (file: any) => {
    return false;
  };

  return (
    // <PageHeaderWrapper title={false} breadcrumb={undefined}>
    <>
      <ProTable
        headerTitle=""
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            disabled={thestate == 3}
            icon={<UploadOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('上传自检附件');
              form.setFieldsValue({
                inspectionType: '过程检验',
                id: theid,
              });
              setModalVisit(true);
            }}
            type="primary"
          >
            上传附件
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTranNew(ref.current.getFieldsValue());
          //     exportInspectionFileInfo({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `InspectionFileInfo.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params, productManufactInforId: theid, inspectionType: '过程检验' };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          const result = await getInspectionFileInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 700, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        destroyOnClose
      >
        <Form.Item label="标识id" name="id" hidden={true}>
          <Input disabled />
        </Form.Item>
        <Form.Item
          label="检验类型"
          name="inspectionType"
          rules={[{ required: true, message: '请选择检验类型!' }]}
        >
          <Input disabled placeholder="过程检验" />
        </Form.Item>
        <Form.Item
          label="选择文件"
          name="file"
          rules={[{ required: true, message: '请上传文件!' }]}
        >
          <Upload
            //listType="picture-card"
            file-list="fileList"
            onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
            showUploadList={true}
            beforeUpload={beforeUpload}
            multiple={true}
          >
            <Button icon={<UploadOutlined />}>上传文件</Button>
          </Upload>
        </Form.Item>
      </Modal>
      {/* </PageHeaderWrapper> */}
    </>
  );
};
export default InspectionFileInfo;
